package com.csc.banking.dao;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.csc.banking.model.Customer;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;

@Component
public class CustomerDao  extends GenaricDao
{
	@PersistenceContext private EntityManager em;
	
	@Override	
	Class<?> getEntityClass() 
	{
		return Customer.class;
	}
	
	public Customer getCustomer(String userName) 
	{
    	TypedQuery<Customer> query = em.createQuery(
            "SELECT g FROM Customer g where LOWER(g.userName)=:userName", Customer.class).setParameter("userName", userName.trim().toLowerCase());
    	try
    	{
    		return query.getSingleResult();
    	}
    	catch(Exception e)
    	{    		
    	}
    	return null;
    }
	
	private String getMD5(String s)
	{
		MessageDigest md=null;
		try 
		{
			md = MessageDigest.getInstance("MD5");
		}
		catch (NoSuchAlgorithmException e1) 
		{
		}
	    md.update(s.getBytes());
	    byte byteData[] = md.digest();
	    
	    StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) 
        {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
	}
	
	public Customer getCustomer(String userName, String password)
	{		
	    
		password=getMD5(password);
		TypedQuery<Customer> query = em.createQuery(
            "SELECT g FROM Customer g where LOWER(g.userName)=:userName AND g.password=:password", Customer.class).setParameter("userName", userName.trim().toLowerCase()).setParameter("password", password);
    	try
    	{
    		return query.getSingleResult();
    	}
    	catch(Exception e)
    	{    		
    	}
    	return null;
    }
	
	public List<Customer> getAllCustomers() 
	{
    	TypedQuery<Customer> query = em.createQuery(
            "SELECT g FROM Customer g ORDER BY g.userName", Customer.class);
    	return query.getResultList();
    }
}
